<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
 * 访问链接即可更新缺漏数据
 * https://rongmixiao.com/rmx/tool
 * 有以下数据缺漏问题:
 * 1.部分表后来加了campus_id,通过class_id设置campus_id
 * 2.student表后来加了username字段，对应的x_student_id
*/

class Tool extends BaseController {
    // 定时开关机
    private $powerTimeName = 'brand_power_time';
    private $powerWeekName = 'power_week';
    // 定时开关机v2
    private $powerTimeV2Name = 'brand_power_time_v2';

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        // $this->admin_init();
        // 加载类库
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        $this->load->model('dataModel');
    }

    public function test_wx() {
         // 获取教师信息
         $teacherInfo = $this->schoolModel->get_teacher_info_by_username('18642007585', 53);
         $sessArr = array(
            'qywx' => true,
            // 'openid' => '',
            'user' => $teacherInfo,
            'bind_user_type' => BIND_TYPE_TEACHER
        );
        $this->session->set_userdata('wx', $sessArr);

        // 跳转到手机端个人中心
        $redirectUrl = wx_url("user/index");

        redirect($redirectUrl);
    }

    //  测试
    public function get_hzy_school_list() {
        $this->load->library('haozhuanyeV2');
        $res = $this->haozhuanyev2->get_school_list();
        echo'<pre>';var_export($res);exit;
    }
    public function test() {
        $this->load->library('haozhuanyeV2');
        // $res = $this->haozhuanyev2->get_school_classes(1872);
        $res = $this->haozhuanyev2->get_school_coach(3597);
        echo'<pre>';var_export($res);
        exit;
    }
    // 清楚session
    public function clear_session() {
        $this->session->set_userdata('wx', NULL);
    }
    public function test_get_grade() {
        $this->load->library('haozhuanyeV2');
        $res = $this->haozhuanyev2->get_school_grades(25166696);
        echo'<pre>';var_export($res);
        exit;
    }
    public function test_get_school_admin() {
        $this->load->library('haozhuanyeV2');
        $res = $this->haozhuanyev2->get_school_admin(3597);
        echo'<pre>';var_export($res);
        exit;
    }
    public function test_get_hexi_schedule() {
        $this->load->library('haozhuanyeV2');
        $res = $this->haozhuanyev2->get_school_schedule(25166696);
        echo'<pre>';var_export($res);
        exit;
    }

    public function testMysql() {
        $this->load->library('chaoxing');
        $res = $this->chaoxing->get_school_list();
        echo '<pre>';var_export($res);
        
        $res = $this->chaoxing->get_subject_list(1);
        echo '<pre>';var_export($res);
        exit;
    }
    public function testRedis() {
        $r = new Redis();

        $r->connect('127.0.0.1', 6379);
        $r->auth('');
        var_dump($r->set("key", "value"));
        var_dump($r->get("key"));

        // 云redis需用vpn连接
        // $r->connect('ozzhapqouubf.redis.sae.sina.com.cn', 10046);
        // $r->auth('yie7fZXI9oTZId4EPtpbarGeBiJPUEtahkQK829uzOwVbzuHBQLLv1JKvCTtEiWw');
        // var_dump($r->set("key", "value3"));


    }

    public function test_hzy() {
        $this->load->library('haozhuanyeV2');
        $res = $this->haozhuanyev2->get_school_info(1447);
        echo'<pre>';var_export($res);
        $res = $this->haozhuanyev2->get_school_info(3170);
        echo'<pre>';var_export($res);
        $res = $this->haozhuanyev2->get_school_info(3174);
        echo'<pre>';var_export($res);
        $res = $this->haozhuanyev2->get_school_info(3259);
        echo'<pre>';var_export($res);
        $res = $this->haozhuanyev2->get_school_info(1872);
        echo'<pre>';var_export($res);
        $res = $this->haozhuanyev2->get_school_info(3597);
        echo'<pre>';var_export($res);
        $res = $this->haozhuanyev2->get_school_info(25166696);
        echo'<pre>';var_export($res);
        $res = $this->haozhuanyev2->get_school_info(3264);
        echo'<pre>';var_export($res);
        $res = $this->haozhuanyev2->get_school_info(3563);
        echo'<pre>';var_export($res);
        exit;
    }

    public function index() {
        $this->__set_campus_id();
        $this->__set_student_username();
        $this->__set_student_password();
        $this->__set_teacher_password();
        exit(json('更新数据成功', true));
    }

    // // 同步旧的的班主任数据到执教关系，如果该班级的执教关系已存在，就不处理
    // public function handle_master() {
    //     $this->load->model('staffModel');
    //     // 获取所有班级列表
    //     $classList = $this->classesModel->get_class_list(array(
    //         'isDelete' => 0
    //     ));
    //     // 获取任教关系列表
    //     $coachParams['isDelete'] = 0;
    //     $coachParams['coachType'] = COACH_TYPE_MASTER;
    //     $coachList = $this->staffModel->get_coach_list($coachParams);
    //     $coachList = array_value_to_key($coachList, 'class_id');
    //     $insertBatch = array();
    //     foreach($classList as $class) {
    //         if(isset($class['class_master']) && $class['class_master'] && !isset($coachList[$class['id']])) {
    //             $insertBatch[] = array(
    //                 'school_id' => $class['school_id'],
    //                 'campus_id' => $class['campus_id'],
    //                 'teacher_id' => $class['class_master'],
    //                 'class_id' => $class['id'],
    //                 'coach_type' => COACH_TYPE_MASTER,
    //                 'is_delete' => 0,
    //                 'updatetime' => date('Y-m-d H:i:s'),
    //                 'createtime' => date('Y-m-d H:i:s') 
    //             );
    //         }
    //     }
    //     // 插入数据
    //     if(count($insertBatch)) {
    //         $this->db->insert_batch(StaffModel::$coachTable, $insertBatch);
    //     }
    //     $count = count($insertBatch);
    //     if($count === 0) {
    //         $msg = '班主任数据无须更新';
    //     } else {
    //         $msg = '更新数据成功，更新了' . $count . '条数据';
    //     }
    //     exit(json($msg, true));
    // }

    // 填补微信绑定用户信息，包括昵称，头像和性别
    public function handle_wx_user_info() {
        $this->load->model('wxUserModel');
        $wxUserParams['emptyInfo'] = 1;
        // 获取nickname或headimgurl为空的wx_user
        $wxUserList = $this->wxUserModel->get_wx_user_list($wxUserParams);
        // echo'<pre>';var_export($wxUserList);exit;
        if(!empty($wxUserList)) {
            $this->load->library('wechat');
            $updateBatch = array();
            foreach($wxUserList as $wxUser) {
                $wxUserInfo = $this->wechat->get_user_info($wxUser['openid']);
                if(!empty($wxUserInfo) && isset($wxUserInfo['nickname'])) {
                    array_push($updateBatch, array(
                        'id' => $wxUser['id'],
                        'nickname' => urlencode($wxUserInfo['nickname']),
                        'headimgurl' => $wxUserInfo['headimgurl'],
                        'sex' => isset($wxUserInfo['sex']) ? $wxUserInfo['sex'] : 1
                    ));
                }
            }
            $this->db->update_batch(WxUserModel::$wxUserTable, $updateBatch, 'id');

            exit(json('更新数据成功，更新了' . count($updateBatch) . '条数据', true));
        } else {
            exit(json('微信用户数据无须更新', true));
        }
    }

    // // 解决nickname没有urlencode(只须执行一次)
    // public function handle_wx_user_name() {
    //     $this->load->model('wxUserModel');
    //     $wxUserParams['createtime'] = "2020-05-06 15:36:59";
    //     // 获取nickname或headimgurl为空的wx_user
    //     $wxUserList = $this->wxUserModel->get_wx_user_list($wxUserParams);
    //     // echo'<pre>';var_export($wxUserList);exit;
    //     if(!empty($wxUserList)) {
    //         $this->load->library('wechat');
    //         $updateBatch = array();
    //         foreach($wxUserList as $wxUser) {
    //             $wxUserInfo = $this->wechat->get_user_info($wxUser['openid']);
    //             if(!empty($wxUserInfo) && isset($wxUserInfo['nickname'])) {
    //                 array_push($updateBatch, array(
    //                     'id' => $wxUser['id'],
    //                     'nickname' => urlencode($wxUserInfo['nickname']),
    //                 ));
    //             }
    //         }
    //         $this->db->update_batch(WxUserModel::$wxUserTable, $updateBatch, 'id');

    //         exit(json('更新数据成功，更新了' . count($updateBatch) . '条数据', true));
    //     } else {
    //         exit(json('微信用户数据无须更新', true));
    //     }
    // }

    // // 考勤模式改版，处理旧考勤数据，只能执行一次
    // public function handle_schedule_data() {
    //     // 获取全部考勤数据
    //     $signList = $this->dataModel->get_all_student_sign_list();
    //     // 获取所有班级
    //     $classList = $this->classesModel->get_class_list();
    //     $classList = array_value_to_key($classList, 'id');
    //     $updateBatch = array();
    //     foreach($signList as $sign) {
    //         if($sign['temperature']) {
    //             // 体温监测
    //             $signType = SIGN_TYPE_TEMPERATURE;
    //         } else {
    //             if($sign['sign_type'] == 1 || $sign['sign_type'] == 3) {
    //                 // 刷卡
    //                 $signType = SIGN_TYPE_CARD;
    //             } else {
    //                 // 人脸
    //                 $signType = SIGN_TYPE_FACE;
    //             }
    //         }
    //         $arr = array(
    //             'id' => $sign['id'],
    //             'sign_type' => $signType,
    //             'state' => SIGN_STATE_NORMAL
    //         );
    //         $classId = $sign['class_id'];
    //         if(isset($classList[$classId])) {
    //             if($classList[$classId]['class_type'] == CLASSES_TYPE_NORMAL) {
    //                 // 行政班考勤
    //                 $arr['state'] = SIGN_STATE_NORMAL;
    //             } else {
    //                 // 教学班考勤
    //                 $arr['state'] = SIGN_STATE_TEACH;
    //             }
    //         }
    //         array_push($updateBatch, $arr);
    //     }
    //     if($updateBatch) {
    //         $this->db->update_batch(DataModel::$signTable, $updateBatch, 'id');
    //     }

    //     exit(json('更新数据成功，更新了' . count($updateBatch) . '条数据', true));
    //     // echo'<pre>';var_export(count($updateBatch));exit;
    //     // echo'<pre>';var_export($updateBatch);exit;
    // }

    // 设置毕业年级的年级，班级，学生表`is_graduated` 为1
    public function handle_graduate_data() {
        // 获取毕业默认年级列表
        $defaultGradeParams['isGraduated'] = 1;
        $defaultGradeParams['field'] = 'id';
        $defaultGradeList = $this->classesModel->get_default_grade_list($defaultGradeParams);
        if($defaultGradeList) {
            $defaultGradeIdArr = array();
            foreach($defaultGradeList as $defaultGrade) {
                array_push($defaultGradeIdArr, $defaultGrade['id']);
            }
            // 设置年级表
            $gradeParams['isDelete'] = 0;
            $gradeParams['defaultGradeIdSet'] = implode(',', $defaultGradeIdArr);
            $gradeList = $this->classesModel->get_grade_list($gradeParams);
            if($gradeList) {
                $gradeIdArr = array();
                foreach($gradeList as $grade) {
                    array_push($gradeIdArr, $grade['id']);
                }
                $gradeIdSet = implode(',', $gradeIdArr);
                $this->db->where_in("id", $gradeIdArr);
                $this->db->update(ClassesModel::$gradeTable, array('is_graduated' => 1));
                // 设置班级表
                $classParams['isDelete'] = 0;
                $classParams['gradeIdSet'] = $gradeIdSet;
                $classList = $this->classesModel->get_class_list($classParams);
                if($classList) {
                    $classIdArr = array();
                    foreach($classList as $class) {
                        array_push($classIdArr, $class['id']);
                    }
                    $classIdSet = implode(',', $classIdArr);
                    $this->db->where_in("id", $classIdArr);
                    $this->db->update(ClassesModel::$classTable, array('is_graduated' => 1));
                    // 设置学生表
                    $params['isDelete'] = 0;
                    $params['field'] = "id";
                    $params['classSet'] = $classIdSet;
                    $studentList = $this->schoolModel->get_student_list($params);
                    if($studentList) {
                        $studentIdArr = array();
                        foreach($studentList as $student) {
                            array_push($studentIdArr, $student['id']);
                        }
                        $this->db->where_in("id", $studentIdArr);
                        $this->db->update(SchoolModel::$schoolStudentTable, array('is_graduated' => 1));
                    }
                }
            }
        }
        if(isset($gradeList) && $gradeList) {
            exit(json('数据更新成功', true));
        }
        exit(json('数据无须更新', true));
        // echo'<pre>';var_export($studentList);exit;
    }

    // 定时开关机改版，处理旧数据，插入新数据，只需执行一次
    public function handle_power_time_data() {
        $this->load->model('configModel');
        // 获取所以校区
        $campusParams['isDelete'] = 0;
        $campusList = $this->schoolModel->get_campus_list($campusParams);
        foreach($campusList as $campus) {
            $powerWeekConfigArr = $this->configModel->get_school_campus_config($campus['school_id'], $campus['id'], $this->powerWeekName);
            $powerTimeConfigArr = $this->configModel->get_school_campus_config($campus['school_id'], $campus['id'], $this->powerTimeName);
            // echo'<pre>';var_export($powerWeekConfigArr);

            if($powerTimeConfigArr && $powerTimeConfigArr['config_value'] && $powerTimeConfigArr['config_value'] != '[]') {
                $powerTimeArr = json_decode($powerTimeConfigArr['config_value'], true);
            } else {
                // 未设置，给个默认时间
                $powerTimeArr = array(
                    array(
                        'starttime' => '5:00',
                        'endtime' => '19:00'
                    )
                );
            }

            if($powerWeekConfigArr && $powerWeekConfigArr['config_value'] && $powerWeekConfigArr['config_value'] != '') {
                $powerWeekArr = explode(',', $powerWeekConfigArr['config_value']);
                // echo'<pre>';var_export($powerWeekArr);exit;
            } else {    
                // 未设置，全周开机
                $powerWeekArr = array(1, 2, 3, 4, 5, 6, 7);
            }
            $powerTimeV2Arr = array();
            for($i = 1; $i <= 7; $i++) {
                if(in_array($i, $powerWeekArr)) {
                    $powerTimeV2Arr[$i] = $powerTimeArr;
                } else {
                    $powerTimeV2Arr[$i] = array(); 
                }
            }
            $powerTimeV2Json = json_encode($powerTimeV2Arr, JSON_UNESCAPED_UNICODE);
            // if($campus['school_id'] == 25) {
            //     echo'<pre>';var_export($powerTimeV2Json);exit;
            // }
            // 设置school_config
            $this->configModel->save_school_campus_config($campus['school_id'], $campus['id'], $this->powerTimeV2Name, $powerTimeV2Json);
            // 设置班牌power_time_v2
            $data = array(
                'power_time_v2' => $powerTimeV2Json
            );
            $this->db->update(ClassesModel::$brandTable, $data, array(
                'school_id' => $campus['school_id'],
                'campus_id' => $campus['id'] 
            ));
        }
        exit(json('更新开关机时间成功', true));
    }


    // 更新缺漏的学生账号
    private function __set_student_username() {
        $params['isDelete'] = 0;
        $params['field'] = "id, username, x_student_id";
        // 获取x_student_id不为空的，即同步过来的学生数据
        $params['xStudentId'] = 1;
        $studentList = $this->schoolModel->get_student_list($params);
        foreach($studentList as $student) {
            if($student['username'] !== $student['x_student_id']) {
                $this->db->where('id', $student['id']);
                $this->db->update(SchoolModel::$schoolStudentTable, array('username' => $student['x_student_id']));
            }
        }
    }

    // 更新缺漏的学生密码，默认为123456
    private function __set_student_password() {
        $this->db->where('is_delete', 0);
        $this->db->where('password', '');
        $password = password_hash(123456, PASSWORD_DEFAULT);
        $this->db->update(SchoolModel::$schoolStudentTable, array('password' => $password));
    }
    
    // 更新缺漏的教师密码，默认为123456
    private function __set_teacher_password() {
        $this->db->where('is_delete', 0);
        $this->db->where('password', '');
        $password = password_hash(123456, PASSWORD_DEFAULT);
        $this->db->update(SchoolModel::$schoolUserTable, array('password' => $password));
    }
    
    // 更新缺漏的校区id
    private function __set_campus_id() {
        $this->_set_album_campus_id();
        $this->_set_album_category_campus_id();
        $this->_set_announce_campus_id();
        $this->_set_homework_campus_id();
        $this->_set_news_campus_id();
        $this->_set_notify_campus_id();
        $this->_set_video_campus_id();
    }
    private function _set_album_campus_id() {
        $albumList = $this->contentModel->get_album('');
        foreach($albumList as $album) {
            // 如果album表campus_id不为0，跳过不处理
            if($album['campus_id']) {
                continue;
            }
            $classId = $album['class_id'];
            if(!empty($classId)) {
                $class = $this->classesModel->get_class_info($classId);
                // 更新homework表campus_id
                $this->db->where('id', $album['id']);
                $this->db->update(ContentModel::$albumTable, array('campus_id' => $class['campus_id']));
            }
        }
    }
    private function _set_album_category_campus_id() {
        $albumCategoryList = $this->contentModel->get_album_category('');
        foreach($albumCategoryList as $albumCategory) {
            // 如果campus_id不为0，跳过不处理
            if($albumCategory['campus_id']) {
                continue;
            }
            $classId = $albumCategory['class_id'];
            if(!empty($classId)) {
                $class = $this->classesModel->get_class_info($classId);
                // 更新albumCategory表campus_id
                $this->db->where('id', $albumCategory['id']);
                $this->db->update(ContentModel::$albumCategoryTable, array('campus_id' => $class['campus_id']));
            }
        }
    }
    private function _set_announce_campus_id() {
        $params['isDelete'] = 0;
        $announceList = $this->contentModel->get_announce_list($params);
        foreach($announceList as $announce) {
            // 如果announce表campus_id不为0，跳过不处理
            if($announce['campus_id']) {
                continue;
            }
            // 获取该学校默认校区
            $params['schoolId'] = $announce['school_id'];
            $campusList = $this->schoolModel->get_campus_list($params);
            foreach($campusList as $campus) {
                if($campus['campus_name'] === '默认校区') {
                    $campusId = $campus['id'];
                    break;
                }
            }
            // 如找不到默认校区，获取第一个校区
            $campusId = $campusId ? $campusId : $campusList[0]['id'];
            // 更新announce表campus_id
            $this->db->where('id', $announce['id']);
            $this->db->update(ContentModel::$announceTable, array('campus_id' => $campusId));
        }
    }
    private function _set_homework_campus_id() {
        $params['isDelete'] = 0;
        $homeworkList = $this->contentModel->get_homework_list($params);
        foreach($homeworkList as $homework) {
            // 如果homework表campus_id不为0，跳过不处理
            if($homework['campus_id']) {
                continue;
            }
            $classId = $homework['class_id'];
            if(!empty($classId)) {
                $classIdArr = explode(',', $classId);
                // 取第一个classid
                $classId = $classIdArr[0];
                $class = $this->classesModel->get_class_info($classId);
                // 更新homework表campus_id
                $this->db->where('id', $homework['id']);
                $this->db->update(ContentModel::$homeworkTable, array('campus_id' => $class['campus_id']));
            }
        }
    }
    private function _set_news_campus_id() {
        $params['isDelete'] = 0;
        $newsList = $this->contentModel->get_news_list($params);
        foreach($newsList as $news) {
            // 如果news表campus_id不为0，跳过不处理
            if($news['campus_id']) {
                continue;
            }
            $classId = $news['class_id'];
            if(!empty($classId)) {
                $classIdArr = explode(',', $classId);
                // 取第一个classid
                $classId = $classIdArr[0];
                $class = $this->classesModel->get_class_info($classId);
                // 更新news表campus_id
                $this->db->where('id', $news['id']);
                $this->db->update(ContentModel::$newsTable, array('campus_id' => $class['campus_id']));
            }
        }
    }
    private function _set_notify_campus_id() {
        $params['isDelete'] = 0;
        $notifyList = $this->contentModel->get_notify_list($params);
        foreach($notifyList as $notify) {
            // 如果notify表campus_id不为0，跳过不处理
            if($notify['campus_id']) {
                continue;
            }
            $classId = $notify['class_id'];
            if(!empty($classId)) {
                $classIdArr = explode(',', $classId);
                // 取第一个classid
                $classId = $classIdArr[0];
                $class = $this->classesModel->get_class_info($classId);
                // 更新notify表campus_id
                $this->db->where('id', $notify['id']);
                $this->db->update(ContentModel::$notifyTable, array('campus_id' => $class['campus_id']));
            }
        }
    }
    private function _set_video_campus_id() {
        $params['isDelete'] = 0;
        $videoList = $this->contentModel->get_video_list($params);
        foreach($videoList as $video) {
            // 如果video表campus_id不为0，跳过不处理
            if($video['campus_id']) {
                continue;
            }
            $classId = $video['class_id'];
            if(!empty($classId)) {
                $classIdArr = explode(',', $classId);
                // 取第一个classid
                $classId = $classIdArr[0];
                $class = $this->classesModel->get_class_info($classId);
                // 更新video表campus_id
                $this->db->where('id', $video['id']);
                $this->db->update(ContentModel::$videoTable, array('campus_id' => $class['campus_id']));
            }
        }
    }
}